//
//  SubjectViewController.m
//  ITrip
//
//  Created by dlios on 15-5-21.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "SubjectViewController.h"

@interface SubjectViewController ()<UIAlertViewDelegate>

@end

@implementation SubjectViewController

- (void) dealloc{
    [_dataArray release];
    [_tView release];
    [super dealloc];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 110, 30)];
    title.text = @"  专     题";
    title.font = [UIFont systemFontOfSize:20];
    title.font = [UIFont boldSystemFontOfSize:25];
    title.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = title;
    
    NSString *path = [URLPath subjectURL];
    self.dataArray = [NSMutableArray array];
    
    // 定义菊花控件
    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [self.view addSubview:activityIndicator];
    activityIndicator.color = [UIColor grayColor];
    activityIndicator.center = self.view.center;
    [activityIndicator release];
    [activityIndicator startAnimating];
    
    if (self.IsTopic == 1) {
        UIImage *icon = [UIImage imageNamed:@"iconfont_return"];
        icon = [icon imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStyleDone target:self action:@selector(getBack)];
        [self.navigationItem.leftBarButtonItem release];
    }
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    // 告诉AFN不要解析
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    if (self.IsTopic == 1) {
        path = [path stringByAppendingFormat:@"?destination_id=%ld&page=1", self.topicId];
    } else {
        path = [path stringByAppendingFormat:@"?page=1"];
    }
    
    [manager GET:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        self.dataArray = [SubjectParser getParser:operation.responseData];
        [self createTableView];
        [activityIndicator stopAnimating];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接失败" message:nil delegate:self cancelButtonTitle:@"重新连接" otherButtonTitles:nil, nil];
        alert.delegate = self;
        [alert show];
        [activityIndicator stopAnimating];
    }];
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    // 定义菊花控件
    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    
    [self.view addSubview:activityIndicator];
    activityIndicator.color = [UIColor grayColor];
    activityIndicator.center = self.view.center;
    [activityIndicator release];
    [activityIndicator startAnimating];
    
    NSString *path = [URLPath subjectURL];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    // 告诉AFN不要解析
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    if (self.IsTopic == 1) {
        path = [path stringByAppendingFormat:@"?destination_id=%ld&page=1", self.topicId];
    } else {
        path = [path stringByAppendingFormat:@"?page=1"];
    }
    
    [manager GET:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        self.dataArray = [SubjectParser getParser:operation.responseData];
        [self createTableView];
        [activityIndicator stopAnimating];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接失败" message:nil delegate:self cancelButtonTitle:@"重新连接" otherButtonTitles:nil, nil];
        alert.delegate = self;
        [alert show];
        [activityIndicator stopAnimating];
    }];
    
}


- (void)getBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void) createTableView{

    self.tView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    
    self.tView.delegate = self;
    self.tView.dataSource = self;
    [self.tView release];
    
    [self.view addSubview:self.tView];
    
    //去掉cell中间的线
    self.tView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    // 定义菊花控件
    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    
    [self.view addSubview:activityIndicator];
    activityIndicator.color = [UIColor grayColor];
    activityIndicator.center = self.view.center;
    [activityIndicator release];

    
    
    [self.tView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(reFresh)];
    self.number = 1;
    [self.tView addLegendHeaderWithRefreshingBlock:^{
        [activityIndicator startAnimating];
        NSString *path = [URLPath subjectURL];
        self.dataArray = [NSMutableArray array];
        // 下载
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        if (self.IsTopic == 1) {
            path = [path stringByAppendingFormat:@"?destination_id=%ld&page=1", self.topicId];
        } else {
            path = [path stringByAppendingFormat:@"?page=1"];
        }
        [manager GET:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            self.dataArray = [SubjectParser getParser:operation.responseData];
            [self.tView.header endRefreshing];
            [self.tView reloadData];
            [activityIndicator stopAnimating];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接失败" message:nil delegate:self cancelButtonTitle:@"重新连接" otherButtonTitles:nil, nil];
            alert.delegate = self;
            [alert show];
            [activityIndicator stopAnimating];
        }];
    }];
}



- (void)reFresh
{
    self.number++;
    [self.tView.legendFooter beginRefreshing];
    NSString *path = [URLPath subjectURL];
    //下载数据
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *num = [NSString stringWithFormat:@"%ld", self.number];
    NSString *params = [NSString string];
    if (self.IsTopic == 1) {
        path = [path stringByAppendingFormat:@"?destination_id=%ld&page=%@", self.topicId, num];
    } else {
        path = [path stringByAppendingFormat:@"?page=%@", num];
    }
    [manager GET:path parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject){
        [self.dataArray addObjectsFromArray:[SubjectParser getParser:operation.responseData]];
        [self.tView reloadData];
        [self.tView.footer endRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self.tView.footer endRefreshing];
        [self.tView reloadData];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接失败" message:nil delegate:self cancelButtonTitle:@"重新连接" otherButtonTitles:nil, nil];
        alert.delegate = self;
        [alert show];
    }];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 240;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.dataArray.count;

}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"cell";
    SubjectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[[SubjectTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier] autorelease];
    }
    SubjectModel *model = [SubjectModel getModel];
    if (self.dataArray.count > indexPath.row && indexPath.row >= 0) {
        model = [self.dataArray objectAtIndex:indexPath.row];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setSubjectModel:model];

    return cell;
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //更改nav透明度
    self.navigationController.navigationBar.translucent = YES;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"clearColorBG"] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];

    SubjectSecondViewController *secondController = [[SubjectSecondViewController alloc] init];
    SubjectModel *model1 = [self.dataArray objectAtIndex:indexPath.row];
    secondController.number = model1.id;
    self.tabBarController.tabBar.hidden = YES;
    self.tabBarController.tabBar.translucent = YES;
    if (self.IsTopic == 1) {
        secondController.isTopic = 1;
    }
    [self.navigationController pushViewController:secondController animated:YES];


}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
